package com.library.controller;

import com.library.entity.Admin;
import com.library.entity.Borrow;
import com.library.service.BookService;
import com.library.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 管理员Servlet，处理图书借阅请求信息
 */
@WebServlet("/admin")
public class AdminServlet extends HttpServlet {

    private BookService bookService = new BookServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        if(method==null){
           method = "findAllBorrow";
        }
        //获取当前登录的管理员用户
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        if(method.equals("findAllBorrow")){
            //登陆成功初始进入管理员页面，展示所有需要处理的借阅信息
            String pageStr = request.getParameter("page");
            Integer page = Integer.parseInt(pageStr);
            List<Borrow> list = bookService.findAllBorrowByState(0, page);
            request.setAttribute("list", list);
            request.setAttribute("dataPrePage", 6);
            request.setAttribute("currentPage", page);
            request.setAttribute("pages", bookService.getBorrowPagesByState(0));
            request.getRequestDispatcher("admin.jsp").forward(request, response);
        }else if(method.equals("handle")){
            //如果是handle，则是处理同意或者拒绝此借阅信息
            String idStr = request.getParameter("id");
            String stateStr = request.getParameter("state");
            Integer borrowId = Integer.parseInt(idStr);
            Integer state = Integer.parseInt(stateStr);
            bookService.handleBorrow(borrowId,state,admin.getId());
            //如果是处理借阅信息，则还停留在借阅信息页面
            if(state == 1 || state == 2 ){
                response.sendRedirect("/admin?page=1");
            }else if(state == 3){
                //如果处理归还书籍信息，泽海停留在归还书籍信息界面
                response.sendRedirect("/admin?method=getBorrowed&page=1");
            }
        } else if(method.equals("getBorrowed")){
            //如果是getBorrowed，跳转到还书管理
            String pageStr = request.getParameter("page");
            Integer page = Integer.parseInt(pageStr);
            List<Borrow> list = bookService.findAllBorrowByState(1, page);
            request.setAttribute("list", list);
            request.setAttribute("dataPrePage", 6);
            request.setAttribute("currentPage", page);
            request.setAttribute("pages", bookService.getBorrowPagesByState(1));
            request.getRequestDispatcher("return.jsp").forward(request, response);
        }

    }
}

